const config = require("../config");

const jwt = require("jsonwebtoken");

module.exports = async (ctx, next) => {
  let token = ctx.request.headers.authorization;

  let whiteList = ["/api/user/login"];

  let url = ctx.request.url;

  console.log(url.split("?")[0]);

  try {
    if (!whiteList.includes(url.split("?")[0]) && !/^\/swagger-ui/.test(url)) {
      let info = await jwt.verify(token, config.secret);
      ctx.request.userId = info.id;
      ctx.request.userRole = info.role;
    }
    try {
      await next();
    } catch (error) {
      return;
    }
  } catch (error) {
    console.log(error);

    // ctx.response.status = 401;

    ctx.body = {
      code: 401,
      messgae: "身份验证失败"
    };
  }
};
